package org.smart4j.framework.util;

/**
 * Created by Wangminze on 2016/12/10.
 * @description: 转型操作工具类
 */
public final class CastUtil {

    /**
     * author: Wangminze
     * date: 2016/12/10
     * description: 将对象转为String型
     * @param obj
     * @param defaultValue
     * @return 如果对象为NULL，则返回默认值
     */
    public static String cast2String(Object obj,String defaultValue){
        return obj != null ? String.valueOf(obj) : defaultValue;
    }

    /**
     * author: Wangminze
     * date: 2016/12/10
     * description: 转为double型
     * @param obj
     * @param defaultValue
     * @return 对象为空或转换失败则返回默认值
     */
    public static double cast2Double(Object obj,double defaultValue){
        double doubleValue = defaultValue;
        if(obj != null){
            String strValue = cast2String(obj,String.valueOf(defaultValue));
            if ( StringUtil.isNotEmpty(strValue) ){
                try {
                    doubleValue = Double.parseDouble(strValue);
                }catch (NumberFormatException e){
                    doubleValue = defaultValue;
                }
            }
        }
        return doubleValue;
    }

    /**
     * author: Wangminze
     * date: 2016/12/10
     * description: 转为long型,转换失败则返回默认值
     * @param obj
     * @param defaultValue
     * @return 对象为空或为空白字符时返回默认值
     */
    public static long cast2Long(Object obj,long defaultValue){
        long longValue = defaultValue;
        if(obj != null){
            String strValue = cast2String(obj,String.valueOf(defaultValue));
            if ( StringUtil.isNotEmpty(strValue) ){
                try {
                    longValue = Long.parseLong(strValue);
                }catch (NumberFormatException e){
                    longValue = defaultValue;
                }
            }
        }
        return longValue;
    }

    /**
     * author: Wangminze
     * date: 2016/12/10
     * description: 转为int型,转换失败则返回默认值
     * @param obj
     * @param defaultValue
     * @return 对象为空或为空白字符时返回默认值
     */
    public static int cast2Int(Object obj,int defaultValue){
        int intValue = defaultValue;
        if(obj != null){
            String strValue = cast2String(obj,String.valueOf(defaultValue));
            if ( StringUtil.isNotEmpty(strValue) ){
                try {
                    intValue = Integer.parseInt(strValue);
                }catch (NumberFormatException e){
                    intValue = defaultValue;
                }
            }
        }
        return intValue;
    }


    /**
     * author: Wangminze
     * date: 2016/12/10
     * description: 将对象转换成boolean型
     * @param obj
     * @param defaultValue
     * @return 对象为空或为空白字符时返回默认值
     */
    public static boolean cast2Boolean(Object obj,boolean defaultValue){
        boolean booleanValue = defaultValue;
        if(obj != null){
            booleanValue = Boolean.parseBoolean(cast2String(obj,String.valueOf(defaultValue)));
        }
        return booleanValue;
    }
}
